"""
@Author  : 康帅
@Time    : 2021/7/12 15:22
@Function: dict操作
"""

from operator import itemgetter


def dict_method():
    """
    建立字典数据的方式
    :return:
    """
    a = dict(one=1, two=2, three=3)
    b = {'one': 1, 'two': 2, 'three': 3}
    c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    d = dict([('two', 2), ('one', 1), ('three', 3)])
    e = dict({'three': 3, 'one': 1, 'two': 2})
    print(a == b == c == d == e)


def ordered_dict():
    """
    控制一个字典中元素的顺序
    输出数据按照传入字典中先后顺序排序
    :return:
    """
    from collections import OrderedDict
    import json

    d = OrderedDict()
    d["data_1"] = 1
    d["data_2"] = 2
    d["data_3"] = 3
    d["data_4"] = 4
    for key in d:
        print(key, d[key])
    print(json.dumps(d))


def find_same_dict():
    """
    寻找多个字典中相同的key或者value
    :return:
    """
    dict_a = {"x": 1, "y": 2, "z": 3}
    dict_b = {"x": 1, "y": 2, "j": 3}

    # 查找共同的键
    result = dict_a.keys() & dict_b.keys()
    print(result)
    # 在dict_a中查找不在dict_b中的键
    result = dict_a.keys() - dict_b.keys()
    print(result)
    # 查找共同的（键，值）对
    result = dict_a.items() & dict_b.items()
    print(result)


def operator_itemgetter():
    """
    通过某个关键字排序一个字典列表
    :return:
    """
    rows = [
        {'f_name': 'Brian', 'l_name': 'Jones', 'uid': 1003},
        {'f_name': 'David', 'l_name': 'Beazley', 'uid': 1002},
        {'f_name': 'John', 'l_name': 'Cleese', 'uid': 1001},
        {'f_name': 'Big', 'l_name': 'Jones', 'uid': 1004}
    ]
    # 根据f_name作为key排序
    rows_by_f_name = sorted(rows, key=itemgetter('f_name'))
    print(rows_by_f_name)
    # 根据uid作为key排序
    rows_by_uid = sorted(rows, key=itemgetter('uid'))
    print(rows_by_uid)
    # itemgetter() 函数也支持多个keys
    rows_by_l_f_name = sorted(rows, key=itemgetter('l_name', 'f_name'))
    print(rows_by_l_f_name)
    # itemgetter() 有时候也可以用lambda表达式代替
    lambda_rows_by_f_name = sorted(rows, key=lambda r: r['f_name'])
    print(lambda_rows_by_f_name)
    lambda_rows_by_l_f_name = sorted(rows, key=lambda r: (r['l_name'], r['f_name']))
    print(lambda_rows_by_l_f_name)
    # 同样适用于 min() 和 max() 等函数
    lambda_min_uid = min(rows, key=lambda r: r['uid'])
    print(lambda_min_uid)
    lambda_max_uid = max(rows, key=lambda r: r['uid'])
    print(lambda_max_uid)


if __name__ == '__main__':
    dict_method()
    ordered_dict()
    find_same_dict()
    operator_itemgetter()
